﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VCDIFF.Serialization
{
    public class Serialize
    {
        protected string Path { get; set; }

        /// <summary>
        /// Serialize constructor.
        /// </summary>
        /// <param name="path">File path.</param>
        public Serialize(string path)
        {
            Path = path;
        }

        /// <summary>
        /// Writes a VCDIFF Header in a file.
        /// </summary>
        public void WriteHeader()
        {
            FileStream fs = new FileStream(Path, FileMode.Append, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                byte v = 0xD6;
                byte c = 0xC3;
                byte d = 0xC4;
                byte z = 0x00;

                bw.Write(v); // V
                bw.Write(c); // C
                bw.Write(d); // D
                bw.Write(z); // 0
                bw.Write(z); // 0
                bw.Write(z); // 0
                bw.Write(z); // 0
                bw.Write(z); // 0
                bw.Write(z); // 0
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// Writes bytes in a file.
        /// </summary>
        /// <param name="data">The bytes to write.</param>
        public void Write(byte[] data)
        {
            FileStream fs = new FileStream(Path, FileMode.Append, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(data);
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// Writes characters in a file.
        /// </summary>
        /// <param name="data">The characters to write.</param>
        public void Write(char[] data)
        {
            FileStream fs = new FileStream(Path, FileMode.Append, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(data);
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
        }
    }
}
